# coding=utf-8

# Create your views here.
import json

from django.db.models import Q, Count, When, Sum, Case, IntegerField
from django.forms import model_to_dict
from django.http.response import JsonResponse

from common.base_utils import get_request_params, FancyDict
from common.log import logger
from components.bk.apis.bk_login.get_user import GetUser
from components.generic.templates.cmsi.toolkit.tools import get_user_contact
from esb.exdb.models import App
from extras.models import ESBRecord
from extras.utils import get_qy_wx_user, validate_user_auth, calc_page, get_filters, filter_by_user


def query_esb_record(request):
    """
    查询ESBRecord
    :param request:
    :return:
    """
    try:
        if request.method != 'GET':
            return JsonResponse({'message': 'Request method %s not allowed.' % request.method, 'result': False})
        validate_user_auth(request)
        start, end = calc_page(request)
        filters = get_filters(request)
        logger.info(filters)
        search = request.GET.get('search')
        if search:
            filters.update({'content__icontains': search})
        esb_record = ESBRecord.objects.filter(**filters)
        esb_record = filter_by_user(esb_record, request)
        group_by = request.GET.get('group_by')
        if group_by:
            esb_record = esb_record.values(*group_by.split(',')).annotate(
                count=Sum(Case(When(is_close=0, then=1), default=0),
                          output_field=IntegerField())).order_by()
            esb_codes = [esb.get('platform_code') for esb in esb_record]
            apps = {app.get('code'): {'name': app.get('name'), 'logo': app.get('logo')} for app in
                    App.objects.filter(code__in=esb_codes).values('code', 'name', 'logo')}
            esb_record = [dict(
                r,
                last_msg={'content': json.loads(ESBRecord.objects.filter(
                    platform_code=r.get('platform_code')
                ).first().content), 'create_time': ESBRecord.objects.filter(
                    platform_code=r.get('platform_code')
                ).first().create_time} if ESBRecord.objects.filter(
                    platform_code=r.get('platform_code')
                ).first() else {},
                **apps.get(r.get('platform_code'), {})
            ) for r in esb_record]
            return JsonResponse({'data': esb_record, 'result': True}, safe=False)
        return JsonResponse({'data': {'results': [ins.to_dict() for ins in esb_record[start:end]],
                                      'count': esb_record.count()},
                             'result': True}, safe=False)
    except Exception as e:
        logger.exception('查询esb_record 发生异常：')
        return JsonResponse({'message': str(e), 'result': False}, safe=False)


def update_esb_record(request, record_id):
    """
    更新 ESBRecord
    :param request:
    :param record_id:
    :return:
    """
    if request.method != 'POST':
        return JsonResponse({'message': 'Request method %s not allowed.' % request.method, 'result': False})
    try:
        validate_user_auth(request)
        data = FancyDict(get_request_params(request))
        esb_record = ESBRecord.objects.get(id=record_id)
        esb_record.__dict__.update(**data)
        esb_record.save()
        return JsonResponse({'data': model_to_dict(esb_record), 'result': True})
    except ESBRecord.DoesNotExist:
        return JsonResponse({'message': 'Not found', 'result': False})
    except Exception as e:
        return JsonResponse({'message': str(e), 'result': False})


def update_by_filter(request):
    """
    更新 ESBRecord
    :param request:
    :return:
    """
    if request.method != 'POST':
        return JsonResponse({'message': 'Request method %s not allowed.' % request.method, 'result': False})
    try:
        validate_user_auth(request)
        data = FancyDict(get_request_params(request))
        filters = data.get('filter')
        update = data.get('update')
        if not filters or not update:
            return JsonResponse({'message': 'Request params filter and update is required.', 'result': False})
        esb_record = filter_by_user(ESBRecord.objects.filter(**filters), request)
        esb_record.update(**update)
        return JsonResponse({'data': {}, 'result': True})
    except ESBRecord.DoesNotExist:
        return JsonResponse({'message': 'Not found', 'result': False})
    except Exception as e:
        return JsonResponse({'message': str(e), 'result': False})
